# -*- coding:utf-8 -*-
from .models import *
import re

class DepotAllocateError(RuntimeError):
    pass

class DepotManager(object):
    def __init__(self):
        self.load_from_db()

    def load_from_db(self):
        self.depots = Depot.objects.all()

    def allocate(self, size):
        """分配一个可用的depot并返回.
        将采用这样的机制进行分配:
            优先使用非reserved的仓库中空闲空间最大的, 使得这些仓库能均衡地被使用.
            当非reserved仓库都装不下时, 优先使用reserved仓库中空闲空间最小的.
            实在不能分配时raise DepotAllocateError
        """
        normal_depots = self.depots.filter(reserved=False).order_by('-free_size')
        if len(normal_depots) > 0 and normal_depots[0].free_size >= size:
            result = normal_depots[0]
            result.update_used_size(size)
            return result

        reserved_depots = self.depots.filter(reserved=True).order_by('free_size')
        for depot in reserved_depots:
            if depot.free_size >= size:
                depot.update_used_size(size)
                return depot

        raise DepotAllocateError("Cannot allocate proper depot!")

depot_manager = DepotManager()

def translate_depot_url(depot_url):
    result = depot_url
    m = re.match(r'^(depot://)(?P<depot_uuid>[^/]+)', depot_url)
    if m:
        try:
            depot = Depot.objects.get(uuid=m.group('depot_uuid'))
            result = depot.path
        except Depot.DoesNotExist:
            pass
    return result